package com.erp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;

import com.alibaba.sdk.android.ams.common.global.AmsGlobalHolder;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.erp.Interface.Observer;
import com.erp.contacts.Contacts;
import com.erp.mclass.CommonObservable;
import com.erp.mclass.UnCeHandler;
import com.erp.util.Myutil;
import com.erp.util.Sputil;
import com.tencent.smtt.sdk.QbSdk;

import org.xutils.x;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/11/3 0003.
 */
public class Myapp extends Application {
    public static int mScreenWidth = 0;
    public static int mScreenHeight = 0;
    private static final String TAG = "Init";
    private static Context mContext;
    private static CommonObservable<Observer> applicationSubject;
    private static CloudPushService pushService;

    public static Context getContext() {
        return mContext;
    }

    public static SharedPreferences.Editor editor;//sp储存器
    public static SharedPreferences sp;//sp提取器

    @Override
    public void onCreate() {
        super.onCreate();
        init();
//        ReGengXing();
        x.Ext.init(this);
        x.Ext.setDebug(false);
        initCloudChannel(this);
        mContext = getApplicationContext();
        DisplayMetrics mDisplayMetrics = getApplicationContext().getResources()
                .getDisplayMetrics();
        Myapp.mScreenWidth = mDisplayMetrics.widthPixels;
        Myapp.mScreenHeight = mDisplayMetrics.heightPixels;
        editor = Sputil.editor("erp");
        sp = Sputil.sp("erp");
        editor.putBoolean("apd", isPad(this));
        editor.putBoolean("Sophix", false);
        editor.commit();
//搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("onViewInitFinished", " onViewInitFinished is " + arg0);
            }
            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
//x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

//    private String rsa = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDOr2rZ/CQkWoAkLVm4/8H/DQ4oWIIZytJtk3XVwKPVudMUfF4uKgS6Ym4+MwFpoA/LNuUYMcI9dTc/G6TV5m22tCdyiJXoySLahFxxSw3DVK0apk3TbJwt++Ia2AlsG9pPsxBksWwIPNRg5k3NU5mUFSsqChAlVl1AYVR/6E1Ux+uahKkF2l5Xk+olU6PModt5hF4738LF/GFxd9Be7xnVzD73GXw6WB6fPDaKD042gfvhjMe2NX3RZDh2hpHxluEuL9Uh81Cf+sYCeOO+nZiVnXOeHY/aWknVEfpldswSiBMnzFAC/zMIKx6BCTh4ene5LgOcgSjXamzfjSWEUQHJAgMBAAECggEBAKw+U/XFwvjo0tFTWepqeelrn9jPqdyEwki/EvxHxkFe0yHHY1Vlfvs0/FqpdwvncEISRWmcThuZi6j0CLKZjeUszZMNcKDGvl0M4V0pBxc5gekrnsALSzynJQ7p6zBFJfI1b/v6P+W9i+AVDdGHUf2uhoJKUJpNFvmIIztVBN0ZHqq58TH7K8c7aVB+BEiHf/mBVtaIUL6GV/mgv9n7h8hn0du5yg99xkwUECIK71IMb4ickGv+AcUe982dnCGcrObDenB2ZQbBfrpvqBy+pgRp/Piqw9/aAFDeHoa4rOJmovTIzktCzYknDuA/UtSNurWE/iStIIOEP5ttgXZtKWECgYEA8y/4A5/hZ709pxvVemqYSW3MFvLp02XI+iu7glWxYwHkUcFIpdPU/m42Wu/feIY3QUMMNFGS4U0amsjIPWm5UeFMk/11//Fa+0abiIOA3q0h/vOvrEdiQ7c7vdrtplUEz1PFmbkBdPZT2XNx2hLWaylEgtbHKykMs/3a28vE8NMCgYEA2ZMem6r8dgxCnDoX9O4Jrj1cezh3KDp7XpKtrHGVJtD7o9jg0nUGV5roGh7g5Qoest7xQL6ZxbZrTb+kaSiKlVJJIaAnkZE7iJssgMiPpShEQH5Ljo2xCgC+4MKsmpH1+/c4KGB8JSI0wKZ60XXzLHU2/pvAMPnAqkveBoF4AXMCgYAPDtdSkiHI5KTephCP5e3MDipm+V+VIWZSZ0bTCS9UrBdRIKC48+bqYjSnaNbzhYwCVH569tobbUTKdMhBVTyOX174guc9k9pIWNTknQ/rudizCq/EAR+KhdwDI303oWgM1mkT3arDbUU/37AbCrOQKxv85gOrHn2U35Efrvxg1QKBgCqiQ3spdDMFj//g+lTKWCdGatrSY7cETqxnfZSu5RUoGkcu9k8HE2kTN6v2pQb8hqtyOEABmUw+xKQFi4f3o8BC0YW/RkGl/c506bGKm2s3irhAhzm11h0prD2KqBvZwiPPe7edwHXeUAv4E1T8EdyCU3ZsuqpeJjy4hRctQ4C1AoGAXaHyODzjE9MLZoMN02XCnJccSpNzQCkjPbdZUmZ0Ys2WAs9+kM5lw1uaZttStii9rLEBMY22KX2zqLFYKd2DZGV/Bvq7qqbhUIjKLS3eC3Kg+/Xnn4F2CROrB44oeMdhswE/og2iqJaRRQgW4Q26WO6bn/byME+yGhEr1hffKwA=";
    public static boolean isXing = false;

//    public void ReGengXing() {
//        isXing = false;
//        SophixManager.getInstance().setContext(this)
//                .setAppVersion("1.3.28")
//                .setAesKey(null)
//                .setEnableDebug(true)
//                .setSecretMetaData("23596523-1", "262de012cfb59b6dbd0cd4ec453596f6", rsa)
//                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
//                    @Override
//                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {
//                        // 补丁加载回调通知
//                        if (code == PatchStatus.CODE_LOAD_SUCCESS) {
//                            // 表明补丁加载成功
//                        } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
//                            Log.d("SophixManager", "补丁下载成功");
//                            isXing = true;
//                            // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启;
//                            // 建议: 用户可以监听进入后台事件, 然后调用killProcessSafely自杀，以此加快应用补丁，详见1.3.2.3
//                        } else {
//                            // 其它错误信息, 查看PatchStatus类说明
//                        }
//                    }
//                }).initialize();
//// queryAndLoadNewPatch不可放在attachBaseContext 中，否则无网络权限，建议放在后面任意时刻，如onCreate中
//
//    }

//    public CommonObservable<Observer> getApplicationSubject() {
//        if (applicationSubject == null) {
//            applicationSubject = new CommonObservable<>();
//        }
//        return applicationSubject;
//    }

    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 初始化云推送通道
     *
     * @param applicationContext
     */
    @SuppressLint("CommitPrefEdits")
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        AmsGlobalHolder.getDefaultSharedPreferences().edit().clear();
        pushService = PushServiceFactory.getCloudPushService();
        pushService.setAppkey(BuildConfig.appKeyPre + getResources().getString(R.string.appKeyPre) + Contacts.appKeyPre() + "3");
        pushService.setAppSecret(BuildConfig.appSecret + getResources().getString(R.string.appSecret) + Contacts.appSecret() + "ec453596f6");
//        pushService.setAppkey("23588208");
//        pushService.setAppSecret("96fd63d7ff6615cdf524cf6b8a21eb46");

//        pushService.setAppkey("23517947");
//        pushService.setAppSecret("9874790694152a33ca9b19112f425c0a");

//        pushService.setAppkey("23596523");
//        pushService.setAppSecret("262de012cfb59b6dbd0cd4ec453596f6");
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d("TAAAG", "init cloudchannel success");
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.d("TAAAG", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Log.d("TAAAG", "8.0");
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "1";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "notification channel";
            // 用户可以看到的通知渠道的描述
            String description = "notification description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM),null);
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
//        9fcd8a8f263e44b391fa2592443530f9
//       初始化小米通道，自动判断是否支持小米系统推送，如不支持会跳过注册
//        MiPushRegister.register(applicationContext, "小米AppID", "小米AppKey");
//         初始化华为通道，自动判断是否支持华为系统推送，如不支持会跳过注册
//        HuaWeiRegister.register(applicationContext);
        Log.d("TAAAG", "设备id="+pushService.getDeviceId());
//        Log.d(TAG,pushService.getDeviceId());23e75f923d4a47358c55bd9ef9ec73ae
    }

    public static CloudPushService getpushService() {
        return pushService;
    }


    public static ArrayList<Activity> list = new ArrayList<Activity>();

    public void init() {
        //设置该CrashHandler为程序的默认处理器
        UnCeHandler catchExcep = new UnCeHandler(this);
        Thread.setDefaultUncaughtExceptionHandler(catchExcep);
    }

    /**
     * Activity关闭时，删除Activity列表中的Activity对象
     */
    public void removeActivity(Activity a) {
        list.remove(a);
    }

    /**
     * 向Activity列表中添加Activity对象
     */
    public void addActivity(Activity a) {
        list.add(a);
        Myutil.Mylog("TAAAAAG", list.toString());
    }

//    /**
//     * 关闭Activity列表中的所有Activity
//     */
//    public void finishActivity() {
//        for (Activity activity : list) {
//            if (null != activity) {
//                activity.finish();
//            }
//        }
//        //杀死该应用进程
//        android.os.Process.killProcess(android.os.Process.myPid());
//    }
}
